package org.simplextensions.registry.phaselisteners;

import java.util.Collection;

import javassist.bytecode.annotation.Annotation;

import org.simplextensions.annotations.ExtensionValidator;
import org.simplextensions.annotations.ExtensionValidators;
import org.simplextensions.registry.Bundle;
import org.simplextensions.registry.EScanPhaseListener;
import org.simplextensions.registry.ExtensionPoint;
import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.registry.IExtensionValidator;
import org.simplextensions.scanner.ScannHelper;

public class ValidatorsScanPhaseListener extends EScanPhaseListener {

	public void scanClass(IExtensionRegistry extensionRegistry, Bundle bundle, String className, Annotation a) {
		if (ExtensionValidator.class.getCanonicalName().equals(a.getTypeName())) {
			scanValidator(extensionRegistry, bundle, className, a);
		} else if (ExtensionValidators.class.getCanonicalName().equals(a.getTypeName())) {
			scanValidators(extensionRegistry, bundle, className, a);
		}
	}

	private void scanValidators(IExtensionRegistry extensionRegistry, Bundle bundle, String className, Annotation a) {
		Annotation[] annotationsValue = ScannHelper.getAnnotationsValue(a, "value");
		for (Annotation a2 : annotationsValue) {
			scanValidator(extensionRegistry, bundle, className, a2);
		}
	}

	private void scanValidator(IExtensionRegistry extensionRegistry, Bundle bundle, String className, Annotation a) {
		Collection<ExtensionPoint> extensionPointsByClass = extensionRegistry.getExtensionPointsByClass(className);

		try {
			Class<IExtensionValidator> classValue = (Class<IExtensionValidator>) ScannHelper.getClassValue(a, "value");
			for (ExtensionPoint ep : extensionPointsByClass) {
				ep.addValidator(classValue.newInstance());
			}
		} catch (Exception e) {
			// TODO: some way to invalidate extension point
			e.printStackTrace();
		}

	}

}
